package com.waves.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 调用专用EventLoop进行处理
 */
@Slf4j
public class HandlerServer {
    public static void main(String[] args) {
        // 创建一个专门处理慢事件的EventLoop
        DefaultEventLoopGroup slowHandler = new DefaultEventLoopGroup(1);

        new ServerBootstrap()
                .group(new NioEventLoopGroup(1), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast("handler1",new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                log.debug("handler1---> {}", msg);
                                ctx.fireChannelRead(msg);
                            }
                        }).addLast(slowHandler, "slowHandler", new ChannelInboundHandlerAdapter(){
                            // 调用专用EventLoop进行处理
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                log.debug("slowHandler----> {}", msg);
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
